﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Xml;
using System.Security.Principal;
using OpenHardwareMonitor.Hardware;

namespace RemoteHardwareMonitor
{
    class RemoteHardwareMonitor
    {
        HardwareMonitorProvider hardwareMonitor = new HardwareMonitorProvider();
        WCFHttpProvider commsProvider = new WCFHttpProvider();
        WebServer server = new WebServer();
        TimerCallback startWebServerCallback;
        Timer startWebServerTimer;

        public delegate void SuccessfulHardwarePoll(object sender, EventArgs e);

        /// <summary>
        /// Admin required for HttpListener and so OpenHardwareMonitor can access CPU temperature (at least on my Gigabyte + X3360 system)
        /// </summary>
        public RemoteHardwareMonitor()
        {
            if (!isAdministrator())
            {
                Console.WriteLine("The application is not running with administrator privileges. Some features will not be available."); 
            }
            
        }


        public void Run()
        {
            // using a single-shot timer as the timer callback method will be run on a different thread, allowing this one to continue to ReadLine()
            startWebServerCallback = this.startWebServer;
            startWebServerTimer = new Timer(startWebServerCallback, null, 0, System.Threading.Timeout.Infinite);
            Console.ReadLine();
            commsProvider.Stop();
            server.Stop();
        }

        private static bool isAdministrator()
        {
            WindowsIdentity identity = WindowsIdentity.GetCurrent();
            WindowsPrincipal principal = new WindowsPrincipal(identity);
            return principal.IsInRole(WindowsBuiltInRole.Administrator);
        }


        private void startWebServer(object state)
        {
            server.RunServer();
        }
    }
}
